package com.imooc.service.impl;

import com.imooc.dto.OrderDto;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.service.BuyerService;
import com.imooc.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 功能描述: <br>
 * (校验订单service)
 *
 * @Author:Mr. xyb
 * @param:
 * @Date: 2018/5/18 15:01
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    /**
     * 查询单个订单
     * 需要校验openid是否一致
     *
     * @param openid
     * @param orderId
     * @return
     */
    @Override
    public OrderDto findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    /**
     * 取消订单
     * 需要校验openid是否一致
     *
     * @param openid
     * @param orderId
     * @return
     */
    @Override
    public OrderDto cancelOrder(String openid, String orderId) {
        // 校验
        OrderDto orderDto = checkOrderOwner(openid, orderId);
        // 如果订单不存在，则抛异常
        if (orderDto == null) {
            log.error("【取消订单】查询不到该订单，orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        // 取消订单
        return orderService.cancel(orderDto);
    }


    /**
     * (校验openid是否一致)
     *
     * @param openid
     * @param orderId
     * @return
     */
    private OrderDto checkOrderOwner(String openid, String orderId) {
        OrderDto orderDto = orderService.findOne(orderId);// 查询订单
        if (orderDto == null) {
            return null;
        }
        /*判断是否为当前用户的订单  ‘equalsIgnoreCase’ 忽略大小写比较*/
        if (!orderDto.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】订单openid不一致，openid={},orderId={}", openid, orderId);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDto;
    }
}